package com.easy.facilitaterecycleadapter.adapter;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

/**
 * Created by Sigthp-P-Department on 2018/5/9.
 */

public class RefreshAndLoaderRecyclerView extends RefreshRecyclerView{
    // 下拉刷新的辅助类
    private LoaderViewCreator mLoaderViewCreator;
    // 手指按下的Y位置
    private int mFingerDownY;
    // 当前是否正在拖动
    private boolean mCurrentDrag = false;
    // 上拉加载更多头部的高度
    private int mLoadViewHeight = 0;
    // 上拉加载更多的头部View
    private View mLoadView;
    // 当前的状态
    private int mCurrentLoadStatus;
    // 默认状态
    public int LOAD_STATUS_NORMAL = 0x0055;
    // 上拉加载更多状态
    public static int LOAD_STATUS_PULL_DOWN_REFRESH = 0x0066;
    // 松开加载更多状态
    public static int LOAD_STATUS_LOOSEN_LOADING = 0x0077;
    // 正在加载更多状态
    public int LOAD_STATUS_LOADING = 0x0088;

    private Adapter adapter=null;

    public RefreshAndLoaderRecyclerView(Context context) {
        super(context);
    }

    public RefreshAndLoaderRecyclerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public RefreshAndLoaderRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    //暴露给用户，自定义一个刷新界面
    public void addViewCreator(LoaderViewCreator viewCreator){
        this.mLoaderViewCreator =viewCreator;
        addRefreshView();
    }

    @Override
    public void setAdapter(Adapter adapter) {
        super.setAdapter(adapter);
        this.adapter=adapter;
        addRefreshView();
    }

    /**
     * 添加刷新功能
     */
    private void addRefreshView() {
        if(adapter != null && mLoaderViewCreator !=null){
            View loadView = mLoaderViewCreator.getLoadView(getContext(), this);
            if(loadView!=null){
                addFooterView(loadView);
                this.mLoadView=loadView;
            }
        }else{
            System.out.println("yanjin-----else--addRefreshView--"+adapter);
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()){
            case MotionEvent.ACTION_DOWN:
                //记录手指按下时的Y轴位置
                mFingerDownY = (int) ev.getRawY();
                break;
            case MotionEvent.ACTION_UP:
                if(mCurrentDrag){
                    restoreLoadView();
                }
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 重置当前加载更多状态
     */
    private void restoreLoadView() {
        int currentBottomMargin = ((MarginLayoutParams) mLoadView.getLayoutParams()).bottomMargin;
        int finalBottomMargin = 0;
        if (mCurrentLoadStatus == LOAD_STATUS_LOOSEN_LOADING) {
            mCurrentLoadStatus = LOAD_STATUS_LOADING;
            if (mLoaderViewCreator != null) {
                mLoaderViewCreator.onLoaderLoading();
            }
            if (mOnLoadMoreListener != null) {
                mOnLoadMoreListener.onLoad();
            }
        }
        int distance = currentBottomMargin - finalBottomMargin;
        // 回弹到指定位置
        ValueAnimator animator = ObjectAnimator.ofFloat(currentBottomMargin, finalBottomMargin).setDuration(distance);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float currentBottomMargin = (float) animation.getAnimatedValue();
                setLoadViewMarginBottom((int) currentBottomMargin);
            }
        });
        animator.start();
        mCurrentDrag = false;
    }

    /**
     * 设置加载View的marginBottom
     */
    public void setLoadViewMarginBottom(int marginBottom) {
        MarginLayoutParams params = (MarginLayoutParams) mLoadView.getLayoutParams();
        if (marginBottom < 0) {
            marginBottom = 0;
        }
        params.bottomMargin = marginBottom;
        mLoadView.setLayoutParams(params);
    }

    @Override
    public boolean onTouchEvent(MotionEvent e) {
        switch (e.getAction()){
            case MotionEvent.ACTION_MOVE:
                // 如果是在最底部才处理，否则不需要处理
                if (canScrollDown() || mCurrentLoadStatus == LOAD_STATUS_LOADING) {
                    // 如果没有到达最顶端，也就是说还可以向上滚动就什么都不处理
                    return super.onTouchEvent(e);
                }
                if (mLoaderViewCreator != null) {
                    mLoadViewHeight = mLoadView.getMeasuredHeight();
                }
                // 解决上拉加载更多自动滚动问题
                if (mCurrentDrag) {
                    scrollToPosition(this.adapter.getItemCount() - 1);
                }

                int loaderDistanceY = (int) ((e.getRawY()-mFingerDownY) * mDragIndex);
                if (loaderDistanceY < 0) {
                    setLoadViewMarginBottom(-loaderDistanceY);
                    updateLoadStatus(-loaderDistanceY);
                    mCurrentDrag = true;
                    return true;
                }
                break;
        }
        return super.onTouchEvent(e);
    }

    /**
     * 更新加载的状态
     */
    private void updateLoadStatus(int distanceY) {
        if (distanceY <= 0) {
            mCurrentLoadStatus = LOAD_STATUS_NORMAL;
        } else if (distanceY < mLoadViewHeight) {
            mCurrentLoadStatus = LOAD_STATUS_PULL_DOWN_REFRESH;
        } else {
            mCurrentLoadStatus = LOAD_STATUS_LOOSEN_LOADING;
        }
        if (mLoaderViewCreator != null) {
            mLoaderViewCreator.onPullLoader(distanceY, mLoadViewHeight, mCurrentLoadStatus);
        }
    }

    /**
     * @return Whether it is possible for the child view of this layout to * scroll up. Override this if the child view is a custom view. * 判断是不是滚动到了最顶部，这个是从SwipeRefreshLayout里面copy过来的源代码
     */
    public boolean canScrollDown() {
        return ViewCompat.canScrollVertically(this, 1);
    }

    /**
     * 停止加载更多
     */
    public void onStopLoad() {
        mCurrentLoadStatus = LOAD_STATUS_NORMAL;
        restoreLoadView();
        if (mLoaderViewCreator != null) {
            mLoaderViewCreator.onLoaderStop();
        }
    }

    // 处理加载更多回调监听
    private OnLoadMoreListener mOnLoadMoreListener;
    public void setOnLoadMoreListener(OnLoadMoreListener listener) {
        this.mOnLoadMoreListener = listener;
    }

}
